﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace WqLunTan.Filters
{

    /// <summary>
    /// 全局异常过滤器
    /// </summary>
    public class HttpGlobalExceptionFilter : IExceptionFilter
    {
        readonly ILoggerFactory _loggerFactory;
        readonly IHostingEnvironment _env;

        public HttpGlobalExceptionFilter(ILoggerFactory loggerFactory, IHostingEnvironment env)
        {
            _loggerFactory = loggerFactory;
            _env = env;
        }

        public void OnException(ExceptionContext context)
        {
            var logger = _loggerFactory.CreateLogger(context.Exception.TargetSite.ReflectedType);

            logger.LogError(new EventId(context.Exception.HResult), context.Exception, context.Exception.Message);

            if (_env.IsDevelopment())
            {
                if (context.Exception.InnerException != null)
                {
                    context.Result = new JsonResult(new
                    {
                        msg = context.Exception.InnerException.Message,
                        data = context.Exception.InnerException.StackTrace
                    })
                    { StatusCode = 500 };
                }
                else
                {
                    context.Result = new JsonResult(new
                    {
                        msg = context.Exception.Message,
                        data = context.Exception.StackTrace
                    })
                    { StatusCode = 500 };
                }
            }
            else
            {
                context.Result = new JsonResult(context.Exception.Message) { StatusCode = 500 };
            }

            context.ExceptionHandled = true;
        }

    }
}
